#include <stdio.h>
#include "debug.h"
#include "bleuart.h"
#include "gpioconfig.h"
#include "gpioledinit.h"
#include "ledconfig.h"

uint8_t BleRxData[20];
uint8_t count;
uint8_t bleReceiveState = 0;

void Uart_BleInit(void)
{
    GPIO_InitTypeDef  GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
//    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    GPIO_InitStructure.GPIO_Pin = GPIO_USART2TX;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_USART2RX;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    USART_InitStructure.USART_BaudRate = 9600;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;

    USART_Init(USART2, &USART_InitStructure);
    USART_Cmd(USART2, ENABLE);
}

void BleReceiverData(void)
{
    if (USART_GetFlagStatus(USART2, USART_FLAG_RXNE)) {
        uint8_t bleData = (uint8_t)USART_ReceiveData(USART2);
        if (bleData == 0x5a) {
            count = 0;
            BleRxData[count++] = bleData;
        } else if(bleData == 0xa5) {
            BleRxData[count] = bleData;
            PrintfBleRxData(BleRxData, count+1);
            count = 0;
            bleReceiveState = 1;
        }else {
            BleRxData[count++] = bleData;
        }
    }
}

void BleReceiverDataParse(void)
{
    if (bleReceiveState == 1) {
        bleReceiveState = 0;
        switch (BleRxData[1]) {
            case TYPE_LED1:
                Led1Callback(&BleRxData[3],BleRxData[2]);
                break;
            case TYPE_LED2:
                Led2Callback(&BleRxData[3],BleRxData[2]);
                break;
            default:
                printf("Type Error\r\n");
                break;
        }
    }
}

void PrintfBleRxData(uint8_t *BleRxData, uint8_t len)
{
    printf("Receive Data");
    for (uint8_t i = 0; i < len; i++) {
        printf(":%02x", BleRxData[i]);
    }
    printf("\r\n");
}
